from PyQt5.QtWidgets import *
from PyQt5.QtChart import  QChart,QChartView,QValueAxis,QLineSeries,QSplineSeries
from PyQt5.QtGui import QPen,QColor,QBrush,QFont,QPainter
from PyQt5.QtCore import Qt,pyqtSlot
import serial.tools.list_ports
import numpy as np
import sys,time,random,threading,serial

class QchartForADC(QWidget):
    def __init__(self):
        super(QchartForADC, self).__init__()
        self.TimCount = np.arange(0,11,0.2)
        self.initUI()

    def initUI(self):
        self.setWindowTitle('STM32 ADC GUI')
        self.setGeometry(400,400,1270,615)

        self.CreateChart()

        self.cb1 = QComboBox(self)
        self.cb1.setEnabled(False)

        btn1 = QPushButton('打开')
        btn1.clicked.connect(self.slot_Open)
        btn2 = QPushButton('刷新')
        btn2.clicked.connect(self.slot_Refresh)

        self.usbOkFlag = False
        self.usbRdFlag = False


        self.tb1 = QTextBrowser()

        Hlayout1 = QHBoxLayout()
        Hlayout2 = QHBoxLayout()
        Vlayout1 = QVBoxLayout()
        Hlayout1.addWidget(btn1)
        Hlayout1.addWidget(btn2)
        Hlayout2.addLayout(Hlayout1)
        Hlayout2.addWidget(self.cb1)
        Vlayout1.addLayout(Hlayout2)
        Vlayout1.addWidget(self.tb1)


        grid1 = QGridLayout()


        grid1.addLayout(Vlayout1,0,0)
        grid1.addWidget(self.chartView1,0,1)
        grid1.setColumnStretch(0,1)
        grid1.setColumnStretch(1,5)
        self.setLayout(grid1)
        self.Thread1 = threading.Thread(target=self.test)
        self.Thread1.start()
        self.show()

    def CreateChart(self):
        chart1 = QChart()
        chart1.setTitle('12bit ADC Voltage')

        self.chartView1 = QChartView(self)
        self.chartView1.setChart(chart1)
        self.chartView1.setRenderHint(QPainter.Antialiasing)

        self.series1 = QLineSeries()
        self.series2 = QLineSeries()

        self.series1.setName('ADC1')
        self.series2.setName('ADC2')

        pen1 = QPen(Qt.red)
        pen1.setStyle(Qt.SolidLine)
        pen1.setWidth(2)
        pen2 = QPen(Qt.blue)
        pen2.setStyle(Qt.SolidLine)
        pen2.setWidth(2)

        self.series1.setPen(pen1)
        self.series2.setPen(pen2)

        chart1.addSeries(self.series1)
        chart1.addSeries(self.series2)

        axis1 = QValueAxis()
        axis1.setRange(0,10)
        axis1.setTitleText('Time')
        axis1.setLabelFormat('%.2f')
        axis1.setTickCount(11)
        axis1.setMinorTickCount(4)
        axis1.setGridLineVisible(True)
        axis1.setMinorGridLineVisible(False)

        axis2 = QValueAxis()
        axis2.setRange(0,3.3)
        axis2.setTitleText('Voltage')
        axis2.setLabelFormat('%.2f')
        axis2.setTickCount(11)
        axis2.setMinorTickCount(4)
        axis2.setGridLineVisible(True)
        axis2.setMinorGridLineVisible(False)

        chart1.setAxisX(axis1,self.series1)
        chart1.setAxisY(axis2,self.series1)
        chart1.setAxisX(axis1,self.series2)
        chart1.setAxisY(axis2,self.series2)


    def Series1Updata(self,updataList):
        self.series1.removePoints(0,self.series1.count())
        for i in range(len(updataList)):
            self.series1.append(self.TimCount[i],updataList[i])

    def Series2Updata(self,updataList):
        self.series2.removePoints(0,self.series2.count())
        for i in range(len(updataList)):
            self.series2.append(self.TimCount[i],updataList[i])

    def slot_Refresh(self):
        self.SerList = []
        self.cb1.clear()
        SerInfoList = serial.tools.list_ports.comports(False)
        if len(SerInfoList) != 0:
            for i in range(len(SerInfoList)):
                self.SerList.append(SerInfoList[i].device)

        if len(self.SerList) != 0:
            self.usbOkFlag = True
            self.cb1.setEnabled(True)
            self.cb1.addItems(self.SerList)
            self.tb1.append('\n*****************\n')
            self.tb1.append('发现可用串口:')
            for i in range(len(self.SerList)):
                self.tb1.append("     {COM}".format(COM = self.SerList[i]))
            self.tb1.append('\n*****************\n')

        else:
            self.usbOkFlag = False
            self.tb1.append('\n*****************\n')
            self.tb1.append('没有发现可用串口')
            self.tb1.append('\n*****************\n')

    def slot_Open(self):

        self.tb1.append('\n*****************\n')
        if self.usbOkFlag:
            self.ser = serial.Serial(self.cb1.currentText(),115200)
            if self.ser.isOpen():
                self.tb1.append('串口 '+self.cb1.currentText()+' 已打开')
                self.usbRdFlag = True
            else:
                self.tb1.append('串口 ' + self.cb1.currentText() + ' 打开失败')
                self.usbRdFlag = False
        else:
            self.tb1.append('请先选择串口')
            self.usbRdFlag = False

        self.tb1.append('\n*****************\n')

        TH1 = threading.Thread(target=self.test,args=())
        TH1.start()


    def test(self):
        b = []
        c = []
        if not self.usbRdFlag:
            return

        while True:
            time.sleep(0.1)
            data = self.ser.readline()
            DataList = str(data, encoding='utf-8').split(' ')
            DataList.remove('\n')

            if len(c) < 50:
                c.append(float(DataList[1]))
                self.Series2Updata(c)
            else:
                c.remove(c[0])
                c.append(float(DataList[1]))
                self.Series2Updata(c)

            if len(b) < 50:
                b.append(float(DataList[0]))
                self.Series1Updata(b)
            else:
                b.remove(b[0])
                b.append(float(DataList[0]))
                self.Series1Updata(b)

        return



if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = QchartForADC()
    sys.exit(app.exec_())